import { Input, InputNumber } from '@/components/AntdProxy';
import CommonDrawer from '@/components/CommonDrawer';
import { CrudFormLayout } from '@/components/Crud';
import { ChargeStationSelect } from '@/components/CustomForm';
import { REQUIRED } from '@/constants/rules';
import { Form } from 'antd';
import { useEffect } from 'react';

const SaveStation = (props) => {
  const { open, record, onClose, onOk } = props;
  const [form] = Form.useForm();

  useEffect(() => {
    if (open && record) {
      form.setFieldsValue(record);
    }
  }, [open, record]);

  const handleOk = async () => {
    const values = await form.validateFields();
    onOk?.({
      ...record,
      ...values,
    });
  };

  return (
    <CommonDrawer
      title={record ? '编辑站点' : '添加站点'}
      open={open}
      onClose={onClose}
      onOk={handleOk}
      afterOpenChange={(_open) => {
        if (!_open) {
          form.resetFields();
        }
      }}
    >
      <Form form={form} layout="vertical">
        <CrudFormLayout itemMinWidth={250}>
          <Form.Item label="充电站" name="chargeStationId" rules={[REQUIRED]}>
            <ChargeStationSelect
              onChange={(_, _option) => {
                form.setFieldsValue({
                  chargeStationName: _option?.chargeStationName,
                });
              }}
            />
          </Form.Item>
          <Form.Item label="充电站名称" name="chargeStationName">
            <Input disabled />
          </Form.Item>
          <Form.Item
            label="距离下一站时间（分）"
            name="nextTimes"
            initialValue={0}
            rules={[REQUIRED]}
          >
            <InputNumber />
          </Form.Item>
          <Form.Item
            label="到下一站距离（km）"
            name="nextMileages"
            initialValue={0}
            rules={[REQUIRED]}
          >
            <InputNumber />
          </Form.Item>
        </CrudFormLayout>
      </Form>
    </CommonDrawer>
  );
};

export default SaveStation;
